package system

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"go-papers/models"
	"go-papers/pkg/lognew"
	"go-papers/tools"
	"go-papers/tools/app"
	"go-papers/tools/app/msg"
)

// @Summary 分页部门列表数据
// @Description 分页列表
// @Tags 部门
// @Param name query string false "name"
// @Param id query string false "id"
// @Param position query string false "position"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /backend/deptList [get]
// @Security
func GetDeptList(c *gin.Context) {
	var Dept models.Dept
	Dept.DeptName = c.Request.FormValue("deptName")
	Dept.Status = c.Request.FormValue("status")
	Dept.DeptId, _ = tools.StringToInt(c.Request.FormValue("deptId"))
	Dept.DataScope = tools.GetUserIdStr(c)
	result, err := Dept.SetDept(true)
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}

	app.OK(c, result, "")
}

func GetDeptTree(c *gin.Context) {
	var Dept models.Dept
	Dept.DeptName = c.Request.FormValue("deptName")
	Dept.Status = c.Request.FormValue("status")
	Dept.DeptId, _ = tools.StringToInt(c.Request.FormValue("deptId"))
	Dept.OrganId, _ = tools.StringToInt(c.Request.FormValue("organId"))
	result, err := Dept.SetDept(false)
	if err != nil {
		app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
		return
	}
	lognew.Info(c, "deptError", lognew.Fields{"dep": Dept})

	if len(result) <= 0 && Dept.OrganId > 0 {
		//创建默认 部门 职位
		dep := models.Dept{
			ParentId: 3,
			TopId:    3,
			DeptPath: "",
			DeptName: "默认部门",
			DeptDesc: "默认部门",
			DeptNums: 0,
			Sort:     1,
			OrganId:  Dept.OrganId,
			Status:   "1",
		}
		depresult, err := dep.Create() // 部门列表 为空 初始化
		if err != nil {
			lognew.Error(c, "deptError", lognew.Fields{"err": err.Error(), "dep": dep})
		} else if depresult.DeptId > 0 {
			pos := models.Post{
				DeptId:   depresult.DeptId,
				DeptName: "默认部门",
				PostName: "默认职务",
				PostCode: "DeptAdmin_" + tools.IntToString(depresult.DeptId),
				PostNums: 0,
				Sort:     1,
				Status:   "1",
				Remark:   "系统默认生成",
			}
			_, err = pos.Create()
			if err != nil {
				lognew.Error(c, "postError", lognew.Fields{"err": err.Error(), "pos": pos})
			}

		}
	}

	app.OK(c, result, "")
}

// @Summary 部门列表数据
// @Description 获取JSON
// @Tags 部门
// @Param deptId path string false "deptId"
// @Param position query string false "position"
// @Success 200 {object} app.Response "{"code": 200, "data": [...]}"
// @Router /backend/dept/{deptId} [get]
// @Security
func GetDept(c *gin.Context) {
	var Dept models.Dept
	Dept.DeptId, _ = tools.StringToInt(c.Param("id"))
	Dept.DataScope = tools.GetUserIdStr(c)
	result, err := Dept.Get()
	tools.HasError(err, msg.NotFound, 404)
	app.OK(c, result, msg.GetSuccess)
}

// @Summary 添加部门
// @Description 获取JSON
// @Tags 部门
// @Accept  application/json
// @Product application/json
// @Param data body models.Dept true "data"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /backend/dept [post]
// @Security Bearer
func InsertDept(c *gin.Context) {
	var data models.Dept
	err := c.ShouldBindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据解析失败："+err.Error(), nil)
		return
	}

	uid := tools.GetUserId(c)
	var user models.SysUser
	userInfo, _ := user.GetById(uid)
	data.OrganId = userInfo.OrganId

	data.TopId = tools.StrToInt(err, userInfo.UserType)
	data.CreateBy = tools.GetUserIdStr(c)
	result, err := data.Create() // 新增
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, msg.CreatedSuccess)
}

// @Summary 修改部门
// @Description 获取JSON
// @Tags 部门
// @Accept  application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body models.Dept true "body"
// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
// @Router /backend/dept [put]
// @Security Bearer
func UpdateDept(c *gin.Context) {
	var data models.Dept
	err := c.ShouldBindWith(&data, binding.JSON)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	if data.DeptNums == 0 {
		//查询人数
		var userIn models.SysUser
		userIn.DeptId = data.DeptId
		_, data.DeptNums, _ = userIn.GetPage(1, 10)
	}
	data.UpdateBy = tools.GetUserIdStr(c)
	result, err := data.Update(data.DeptId)
	if err != nil {
		app.ApiResp(c, -1, "数据操作失败："+err.Error(), nil)
		return
	}

	app.OK(c, result, msg.UpdatedSuccess)
}

// @Summary 删除部门
// @Description 删除数据
// @Tags 部门
// @Param id path int true "id"
// @Success 200 {string} string	"{"code": 200, "message": "删除成功"}"
// @Success 200 {string} string	"{"code": -1, "message": "删除失败"}"
// @Router /backend/dept/{id} [delete]
func DeleteDept(c *gin.Context) {
	var data models.Dept
	id, err := tools.StringToInt(c.Param("id"))
	if id == 0 {
		app.Error(c, 500, err, "参数错误，部门id为空")
	}
	_, err = data.Delete(id)
	tools.HasError(err, "删除失败", 500)
	app.OK(c, "", msg.DeletedSuccess)
}

func GetDeptTreeRoleselect(c *gin.Context) {
	var Dept models.Dept
	var SysRole models.SysRole
	id, err := tools.StringToInt(c.Param("roleId"))
	SysRole.RoleId = id
	result, err := Dept.SetDeptLable()
	tools.HasError(err, msg.NotFound, -1)
	menuIds := make([]int, 0)
	if id != 0 {
		menuIds, err = SysRole.GetRoleDeptId()
		if err != nil {
			app.ApiResp(c, -2, "抱歉未找到相关信息："+err.Error(), nil)
			return
		}

	}
	app.Custum(c, gin.H{
		"code":    0,
		"message": "success",
		"data": map[string]interface{}{
			"depts":       result,
			"checkedKeys": menuIds,
		},
		"depts":       result,
		"checkedKeys": menuIds,
	})
}
